package com.example.oss.service;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.oss.entity.Result;
import com.example.oss.entity.ResultEnum;
import com.example.oss.entity.Student;
import com.example.oss.mapper.StudentMapper;
import com.example.oss.util.JwtTokenUtil;
import com.example.oss.util.RedisKeyUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class StudentService {

    @Resource
    private StudentMapper studentMapper;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private RedisTemplate redisTemplate;

    @Value("${jwt.tokenHead}")
    private String tokenHead;

    public Result login(Student student) {
        Student data = getStuentByStuSn(student.getStuSn());
        if (data == null) return Result.failure(ResultEnum.LOGIN_FAILURE);
        boolean matches = passwordEncoder.matches(student.getPassword(), data.getPassword());
        if (matches) {
            //验证成功
            String jwt = jwtTokenUtil.generateToken(student);
            String token = tokenHead + "-" + jwt;

            return Result.success(ResultEnum.LOGIN_SUCCESS, token);
        }
        return Result.failure(ResultEnum.LOGIN_FAILURE);
    }


    public Collection<? extends GrantedAuthority> getAuthorities(int id) {
        Student student = studentMapper.selectById(id);
        List<GrantedAuthority> list = new ArrayList<>();
        list.add(() -> {

            switch (student.getType()) {
                case 1:
                    return "admin";
                default:
                    return "student";
            }
        });
        return list;
    }


    public Student getStuentByStuSn(String stuSn) {
        if (StringUtils.isBlank(stuSn)) return null;
        String userInfoKey = RedisKeyUtil.getUserInfoKey(stuSn);

        Map entries = redisTemplate.opsForHash().entries(userInfoKey);
        if (!CollectionUtils.isEmpty(entries)) {
            return JSON.parseObject(JSON.toJSONString(entries), Student.class);
        } else {
            //走DB
            Student student = studentMapper.selectOne(new QueryWrapper<Student>().eq("stu_sn", stuSn));
            //同步到redis
            Map map = JSON.parseObject(JSON.toJSONString(student), Map.class);
            redisTemplate.opsForHash().putAll(userInfoKey, map);
            return student;
        }
    }
}
